package net.hmr_radio.hmrbot.service;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import net.hmr_radio.hmrbot.meta.KeywordMeta;
import net.hmr_radio.hmrbot.meta.MessageMeta;
import net.hmr_radio.hmrbot.util.PropertyUtil;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.appengine.repackaged.com.google.common.collect.Sets;

public class MessageService {

    private Log log = LogFactory.getLog(MessageService.class);

    private MessageMeta m = MessageMeta.get();

    private KeywordMeta k = KeywordMeta.get();

    /**
     * Yahoo日本語形態素解析で名詞を抜き出す.
     * 
     * @param message
     *            -
     * @return messageに含まれる名詞（よみがな）のSet
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    public Set<String> parse(String message) throws IOException,
            ParserConfigurationException, SAXException {
        log.info("形態素解析 " + message);

        Set<String> result = Sets.newHashSet();

        // if (EnvUtil.isLocal()) {
        // System.setProperty("http.proxyHost", "proxy.apl.co.jp");
        // System.setProperty("http.proxyPort", "8080");
        // }

        URL url = new URL("http://jlp.yahooapis.jp/MAService/V1/parse");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());

        StringBuilder req = new StringBuilder();
        {
            req.append(enc("appid", PropertyUtil.get("yahoo.appid")));
            req.append("&" + enc("sentence", message));
            req.append("&" + enc("results", "ma"));
            req.append("&" + enc("response", "reading"));
            req.append("&" + enc("filter", "9"));
        }
        out.write(req.toString());
        out.flush();
        out.close();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return result;
        }

        DocumentBuilder builder =
            DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document res = builder.parse(conn.getInputStream());
        NodeList words = res.getElementsByTagName("reading");
        for (int i = 0; i < words.getLength(); i++) {
            Element word = (Element) words.item(i);
            result.add(word.getTextContent());
        }

        return result;
    }

    private String enc(String key, String value)
            throws UnsupportedEncodingException {
        return URLEncoder.encode(key, "UTF-8")
            + "="
            + URLEncoder.encode(value, "UTF-8");
    }
}
